#include "mainwindow.h"




MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    openPsFalg = 0;
    noPsFalg = 0;
    messageNum = 0;

    QString s;
    setMaximumSize(0,0);
    setMinimumSize(0,0);
    this->hide();

    createTrayWdiget();//创建托盘工具
    setAutoRecoverPath();

    timer = new QTimer(this);
    timer->setInterval(SL_QUERY_TIME);//5分钟询问一次
    timer->start();

    backupTime.start();

    connect(timer, &QTimer::timeout, this,
            &MainWindow::getProcessId);

    connect(this, &MainWindow::foregroundWindowisPs,
            this, &MainWindow::backupPSDFile);

    this->hide();
}


//创建托盘工具
void MainWindow::createTrayWdiget()
{
    systemTray = new QSystemTrayIcon(this);
    systemTray ->setIcon(QIcon(":/images/tray.png"));
    systemTray->show();

    systemTray->setToolTip("瞅啥瞅，赶紧画画去");
    systemTray->showMessage("小公举小公举我来啦","赶紧赶紧画画去呢，你不画画我无聊╮(╯_╰)╭",QSystemTrayIcon::Information,5000);

    createTrayActions();

}

void MainWindow::createTrayActions()
{
    actionShow = new QAction(this);
    actionQuit = new QAction(this);
    actionHelp = new QAction(this);
    actionAbout = new QAction(this);
    actionSetting = new QAction(this);

    actionShow->setText(QString("显示"));
    actionQuit->setText(QString("退出"));
    actionHelp->setText(QString("帮助"));
    actionAbout->setText(QString("关于"));
    actionSetting->setText(QString("设置"));

    trayiconMenu = new QMenu(this);
    systemTray->setContextMenu(trayiconMenu);
//    trayiconMenu->addAction(actionShow);

//    trayiconMenu->addAction(actionHelp);
    trayiconMenu->addAction(actionAbout);
//    trayiconMenu->addAction(actionSetting);
    trayiconMenu->addAction(actionQuit);


    connect(actionQuit,&QAction::triggered,this,&MainWindow::close);
    connect(actionAbout,&QAction::triggered,this,&MainWindow::aboutPsAutoSave);

}

//备份PSD文件
void MainWindow::backupPSDFile()
{

    //一小时进行一次弹窗提醒
    if ( (messageTime.elapsed()/1000.0) > SL_REMID_TIME  || messageNum == 0 )//SL_REMID_TIME分钟提醒一次
    {
        systemTray->showMessage(tr("小呆瓜"),tr("还不赶紧按ctrl+s，是不是又想重画了"),QSystemTrayIcon::Information,5000);
        messageTime.start();
        messageNum++;
    }

    if ( messageNum > 2 )
    {
        messageNum = 1;
        systemTray->showMessage(tr("揉揉眼睛"),tr("画这么久了，小心累坏了嗷，起来放松放松！"),QSystemTrayIcon::Information,5000);
    }

    //如果距离上一次备份小于5分钟，则返回
    if ( (backupTime.elapsed()/1000.0) < SL_SAVE_TIME )//15分钟保存一次
        return ;

    backupTime.start();

    QDir *temp = new QDir;
    QString backPath = "D:\\slanPSBBackups\\";
    qDebug() << backPath;
    bool exist = temp->exists(backPath);

    if( !exist )
    {
        bool ok = temp->mkdir(backPath);
        if( !ok )
            QMessageBox::warning(this,tr("错误"),tr("文件夹创建失败！"));
    }

    clearDirFile(backPath);//清理多余的，保留20个历史文件

    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString currentDate = currentDateTime.toString("yyyyMMddhhmmss");

    backPath = backPath + currentDate;
    qDebug() << backPath;



    foreach(QString pathTemp, autoRecoverDirPath)
    {
        qDebug() << pathTemp;
        copyDirectoryFiles(pathTemp, backPath);
    }

}


//复制fromDir目录的文件到fromDir目录
bool MainWindow::copyDirectoryFiles(const QString &fromDir, const QString &toDir)
{
    QDir sourceDir(fromDir);
    QDir targetDir(toDir);

    QFileInfoList fileInfoList = sourceDir.entryInfoList();
    if ( fileInfoList.isEmpty() )
        return true;//如果源目录为空，不拷贝

    if(!targetDir.exists())
    {    //< 如果目标目录不存在，则进行创建
        if(!targetDir.mkdir(targetDir.absolutePath()))
            return false;
    }


    foreach(QFileInfo fileInfo, fileInfoList)
    {
        if(fileInfo.fileName() == "." || fileInfo.fileName() == "..")
            continue;

        if(fileInfo.isDir())
        {    //当为目录时，递归的进行copy
            if(!copyDirectoryFiles(fileInfo.filePath(),
                targetDir.filePath(fileInfo.fileName())))
                return false;
        }
        else
        {            // 当允许覆盖操作时，将旧文件进行删除操作
            if( targetDir.exists(fileInfo.fileName()))
            {
                targetDir.remove(fileInfo.fileName());
            }

            // 进行文件copy
            if(!QFile::copy(fileInfo.filePath(),
                targetDir.filePath(fileInfo.fileName())))
            {
                    return false;
            }
        }
    }
    return true;
}


//设置PS自动备份目录
void MainWindow::setAutoRecoverPath()
{
    QDir *temp = new QDir;
    QStringList environment = QProcess::systemEnvironment();
    QString strUSERPROFILE;
    QString path;

    foreach(strUSERPROFILE, environment)
    {
        if (strUSERPROFILE.startsWith("USERPROFILE="))
        {
            strUSERPROFILE = strUSERPROFILE.right( strUSERPROFILE.length() -  strlen("USERPROFILE="));
            break;
        }
    }

    path = strUSERPROFILE + "\\AppData\\Roaming\\Adobe\\Adobe Photoshop CC 2015\\AutoRecover";

    if ( temp->exists(path) )
    {
        autoRecoverDirPath.push_back(path);
    }
    else
        qDebug() << path << " does not exist";

    path = strUSERPROFILE + "\\AppData\\Roaming\\Adobe\\Adobe Photoshop CS6\\AutoRecover";
    if ( temp->exists(path) )
    {
        autoRecoverDirPath.push_back(path);
    }
    else
        qDebug() << path << " does not exist";

}

MainWindow::~MainWindow()
{
    timer->stop();
}


//获取进程ID判断是否为PS
void MainWindow::getProcessId()
{
    DWORD ProcessID;
//    WCHAR ss[255];
    bool inflag = 0;
    PROCESSENTRY32 pe32;// = {0};
    HANDLE hpprocess;

    memset(&pe32, 0, sizeof(PROCESSENTRY32));


    HWND handleWin = GetForegroundWindow();//获得活动窗口ID
    GetWindowThreadProcessId(handleWin, &ProcessID);//通过窗口ID获取进程ID
    qDebug() <<ProcessID;
//    GetProcessImageFileName();
//    GetProcessImageFileName((HANDLE)handleWin,(LPWSTR)ss, sizeof(ss));

    pe32.dwSize = sizeof(pe32);
    //查找进程
    hpprocess = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);//CreateToolhelp32Snapshot创建快照
    BOOL bmore = Process32First(hpprocess,&pe32);

    while (bmore)
    {
        if ( ProcessID == pe32.th32ProcessID)
        {
            QString exeFile = QString::fromWCharArray(pe32.szExeFile);
            if ( exeFile.toLower() == "photoshop.exe")
            {
                inflag = 1;
                noPsFalg = 0;
                if ( openPsFalg == 0 )
                {
                    messageTime.start();
                    openPsFalg = 1;
                }
                emit foregroundWindowisPs();

                break;
            }
            qDebug() <<QString::fromWCharArray(pe32.szExeFile);
        }
        bmore=Process32Next(hpprocess, &pe32);
    }
    //连续三次判断都不是PS，则从计消息提示时间
    if ( inflag == 0 && noPsFalg++ < 3)
    {
        openPsFalg = 0;
    }

//    GetWindowText(GetForegroundWindow(), (LPWSTR)ss, sizeof(ss));//获取当前窗口的标题
//    qDebug() << QString::fromWCharArray(ss);

}




//多过SL_BACKUP_NUM个存档则清理
void MainWindow::clearDirFile(QString & path)
{
    QDir dir(path);

    QStringList infolist = dir.entryList(QDir::NoDotAndDotDot | QDir::AllEntries);
    qDebug() << infolist.size();
    if ( infolist.size() > SL_BACKUP_NUM )
    {
            qDebug()<< removeDirectory(path+infolist.at(0));
    }
}

bool MainWindow::removeDirectory(QString path)
{
    qDebug() << path;
    if (path.isEmpty())
        return false;

    QDir dir(path);
    if(!dir.exists())
        return true;

    dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);
    QFileInfoList fileList = dir.entryInfoList();

    foreach (QFileInfo fi, fileList)
    {
        if (fi.isFile())
            fi.dir().remove(fi.fileName());
        else
            removeDirectory(fi.absoluteFilePath());
    }
    return dir.rmpath(dir.absolutePath());
}

void MainWindow::aboutPsAutoSave()
{
    QMessageBox::about(this, tr("about SlanlPSDAutoSave"),
        tr("<h2> 看你还手欠不保存这下忘不了了吧 </h2>(版本：v%1) "
        "<h3> 作者：史前小虫</h3>"
        "<h3> 本程序送给除了偶尔忘记保存外最可爱最聪明最棒的小懒蛋.</h3>"
        "<p> 本程序用于对PS自动存储的PSD文件进行备份，以防止意外情况导致"
        "尚未保存的数据无法找回，也提供了多时间段的数据存储，可以打开特定时间保存的数据进行再次编写"
        "<p>本程序目前只对对<font color=red>Photoshop CC 2015</font>和<font color=red>Photoshop CS6</font>提供备份支持。"
        "<p>程序自动保存的数据均存储在D:\\slanPSBBackups目录下，5分钟保存一次"
        "文件以保存时间命名"
        "<h4><font color=red>注意：使用程序之前，请确保已经开启Photoshop的文件自动存储恢复功能.存档的PSD文件打开后如果有用，切记保存，否则关闭PS后就会自动删除</h4></font>").arg(SL_VER));
}

